package net.tngou.action.api;

import java.io.IOException;













import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.tngou.action.BaseAction;
import net.tngou.action.BaseServlet;
import net.tngou.http.HttpRequest;
import net.tngou.http.HttpResponse;
import net.tngou.http.RequestContext;
import net.tngou.http.ResponseContext;
import net.tngou.jdbc.DBManager;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



@WebServlet(urlPatterns= {"/api/*","/api"})
public class ServletApi extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private final static Logger log= LoggerFactory.getLogger(ServletApi.class);
	protected static String packages ;//action的路径包
	@Override
	public void init(ServletConfig config) throws ServletException {		
		packages= this.getClass().getPackage().getName(); 
		super.init();	 		
	}
	@Override
	public String getPackages() {
		return packages;
	}
	
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	   
	 HttpRequest request=new RequestContext(req);
	 HttpResponse response = new ResponseContext(resp);	  
	 String module= request.getModule();//取得调用类
	 String action= request.getAction();  //取得调方法
	 BaseAction baseApi =_retrieveModule(module); //初始调用类
	 if (baseApi==null) 
	 {
		 //没有找到Module 返回404
//		response.sendError(HttpServletResponse.SC_NOT_FOUND);//返回404
//		 response.sendRedirect(getDomain(req).getBase()+"/404.html");
		 String json="{\"status\": false,\"code\": 404}";
		 try {
				response.setContentType("application/json; charset=UTF-8");
		        response.setDateHeader("Expires", System.currentTimeMillis()+3600*1000*1);//缓存一小时
		        response.setHeader("Cache-Control", "public,max-age="+3600*1000*1);
	            response.setHeader("Pragma", "Pragma");
		        response.getWriter().print(json);
			} catch (IOException e) {
				log.error("返回application/json{}报错\n"+e,json);

				e.printStackTrace();
			}
		return ;
	 }
	 	
	baseApi.init(request, response); //初始化baseAction
	
	if (StringUtils.isNotEmpty(action))
	{
		baseApi.run(); //执行
	}
	else //默认执行
	{
		try {
			baseApi.execute();
		} catch (ServletException | IOException e) {
			String json="{\"status\":false,\"msg\":\"错误！\"}";
			printJson(json, response);
			e.printStackTrace();
		}finally
		{
			DBManager.closeConnection(); //释放数据库连接到连接池中
		}
		
	}
  }
   
  /**
   * 销毁
   */
  @Override
  public void destroy() {
	  	log.debug("destroy");
		super.destroy();
	}

  
  
  /**
   * 通过类的名称 ，返回名称对于的对象。如果没有找到该对象，返回NULL
   * @param moduleClass 类的名称 如：test.action.TestAction
   * @return 返回 Object对象
   */
  @Override
  protected  BaseAction _retrieveModule(String module) 
  {
	 
	 
	  if(module==null) module="index";
	  module=StringUtils.capitalize(module+"Api");//module后添加Api 并且把第一个字母转为大写
	  String moduleClass=getPackages()+"."+module;
	  //com.mykaoyan.action.TestAction

		try {
				BaseAction baseAction;
				baseAction = (BaseAction) Class.forName(moduleClass).newInstance();
				return baseAction;
			} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
				log.error("没有对用的{}类",moduleClass);
				e.printStackTrace();
			} 
			
		
		return null;
	
  }
  
  protected void printJson(String json,HttpResponse response) {
		try {
			response.setContentType("application/json; charset=UTF-8");
			response.getWriter().print(json);
		} catch (IOException e) {
			log.error("返回application/json{}报错\n"+e,json);
			e.printStackTrace();
		}
		return;
	}

 
  

}
